<?php
/**
 * 合作伙伴
 * 
 * Author: ZeonWang
 * Date: 2018/1/24
 * Time: 8:40
 * Created by PanxSoft.
 */

namespace App\Http\Models;

use App\Observers\BosCleanObserver;
use App\Observers\PartnerObserver;
use App\Services\Utils\Bosable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\UploadedFile;

/**
 * @method self filterName(string $name)
 */
class Partner extends Model
{
    use Bosable;

    protected $table = 'partners';

    protected static $unguarded = true;

    protected $bos_key_prefix = 'partners/';

    public $bos_columns = ['logo'];

    /**
     * @param $logo
     */
    public function setLogoAttribute($logo)
    {
        if (is_file($logo)) {
            $this->attributes['logo'] = $this->uploadPostFile($logo , $this->bos_key_prefix);
        }
    }

    /**
     * 上面的逻辑改了，只能新增一个 logo_key 属性用来测试写入 字符串 key 值
     *
     * @param $logo
     */
    public function setLogoKeyAttribute($logo)
    {
        $this->attributes['logo'] = $logo;
    }

    /**
     * @return null|string
     */
    public function getLogoAttribute()
    {
        if (! $this->attributes['logo']) return null;

        return $this->getStaticUrl($this->attributes['logo']);
    }

    /**
     * @param Builder $query
     * @param $name
     * @return Builder
     */
    public function scopeFilterName(Builder $query, $name)
    {
        if (!$name) return $query;

        return $query->where('name', 'like', '%'.$name.'%');
    }

    /**
     *
     */
    protected static function boot()
    {
        parent::boot();

        /*
         * 监听bos清理事件
         */
        self::observe((BosCleanObserver::class));
    }

}